<template>
  <view class="select-row flex-row" :class="[size, disabled ? 'disabled' : '']" @click="pickerClick">
    <view class="select">
      <view class="flex-row space-between items-center">
        <slot>
          <view :class="selectedText ? 'hasvalue' : 'novalue'" :style="'text-align:' + align">
            {{ selectedText || placeholder }}
          </view>
        </slot>
        <view class="flex-row items-center">
          <view v-if="clearable && selectedText" class="clear_btn" @click.stop="handleClear">
            <text class="cuIcon-roundclosefill" style="color: #c0c4cc"></text>
          </view>
          <text v-if="show_icon" class="arrow cuIcon-right" style="color: #c3c3c3"></text>
        </view>
      </view>
      <myPopup position="bottom" v-model:show="show">
        <view class="option_list">
          <view class="header flex-row">
            <text class="cancel_btn" @click.stop.prevent="show = false">取消</text>
            <text class="tip">{{ tipTitle }}</text>
            <text class="ok_btn" :class="{
              disabled: !tempValue,
            }" @click.stop.prevent="onConfirmSelect">完成</text>
          </view>
          <picker-view :indicator-style="indicatorStyle" :value="pickerValue" @change="onChange" class="picker-view">
            <picker-view-column class="column day" v-if="type != 'time'">
              <view class="item" v-for="(item, index) in yearList" :key="index">{{ item }}</view>
            </picker-view-column>
            <picker-view-column class="column day" v-if="type != 'time'">
              <view class="item" v-for="(item, index) in monthList" :key="index">{{ item }}</view>
            </picker-view-column>
            <picker-view-column class="column day" v-if="type != 'time'">
              <view class="item" v-for="(item, index) in dayList" :key="index">{{ item }}</view>
            </picker-view-column>
            <picker-view-column class="column hour">
              <view class="item" v-for="(item, index) in hourList" :key="index">{{ item }}</view>
            </picker-view-column>
            <picker-view-column class="column minute">
              <view class="item" v-for="(item, index) in minuteList" :key="index">{{ item }}</view>
            </picker-view-column>
            <picker-view-column v-if="showSecond" class="column second">
              <view class="item" v-for="(item, index) in secondList" :key="index">{{ item }}</view>
            </picker-view-column>
          </picker-view>
        </view>
      </myPopup>
    </view>
  </view>
</template>

<script>
import dayjs from "dayjs";
import myPopup from "./myPopup.vue";
export default {
  name: "timeSelter",
  components: {
    myPopup,
  },
  props: {
    // 是否显示清除按钮
    clearable: {
      type: Boolean,
      default: false,
    },
    minYear: {
      type: Number,
      default: () => 5,
    },
    maxYear: {
      type: Number,
      default: () => 5,
    },
    before: {
      type: Number,
      default: 30,
    },
    after: {
      type: Number,
      default: 30,
    },
    showSecond: {
      type: Boolean,
      default: false
    },
    format: {
      //显示时的格式
      type: String,
      default: "YYYY-MM-DD HH:MM:ss",
    },
    valueFormat: {
      //选择后值的格式
      type: String,
      default: "YYYY-MM-DD HH:MM:ss",
    },
    value: {
      type: [String, Number, Date],
      default: "",
    },
    size: {
      //default big large small
      type: [String],
      default: "default",
    },
    disabled: {
      type: [Boolean],
      default: false,
    },
    show_icon: {
      type: [Boolean],
      default: false,
    },
    align: {
      type: String,
      default: "left",
    },
    placeholder: {
      type: String,
      default: "请选择",
    },
    tipTitle: {
      type: String,
      default: "请选择",
    },
    defaultValue: {
      type: String,
      default: "",
    },
    type: {
      type: String,
      default: "datetime",
      validator(prop) {
        let allows = ["date", "datetime", "time"];
        return allows.includes(prop);
      },
    },
  },
  model: {
    prop: "value",
    event: "change",
  },
  data() {
    return {
      show: false,
      indicatorStyle: `height: 40px;`,
      yearList: [],
      monthList: [],
      dayList: [],
      hourList: [],
      minuteList: [],
      secondList: [],
      pickerValue: [],
      tempValue: dayjs(),
    };
  },
  watch: {
    defaultValue: {
      handler(val) {
        console.log("val", val);
        if (val) {
          this.tempValue = val;
        }
      },
      immediate: true,
    },
    value: {
      handler(val) {
        if (val) {
          this.tempValue = val
        }
        this.pickerValue = this.renderPickerValue(val)
      },
      immediate: true,
    },
  },
  computed: {
    selectedText() {
      if (this.value) {
        return dayjs(this.value).format(this.format);
      } else {
        return ""
      }
    },
  },
  created() {
    if (this.type === "date") {
      this.createYear(this.minYear, this.maxYear);
      this.createMonth();
      this.creatDay();
    } else if (this.type === "datetime") {
      this.createYear(this.minYear, this.maxYear);
      this.createMonth();
      this.creatDay();
      this.creatHour();
      this.creatMinute();
      this.creatSecond();
    } else {
      this.creatHour();
      this.creatMinute();
      this.creatSecond();
    }
  },
  methods: {
    renderPickerValue(val = '') {
      let list = []
      if (this.type === "date") {
        list = [
          dayjs().year() - dayjs(val).year() + this.minYear,
          dayjs(val).month(),
          dayjs(val).date() - 1,
        ]
      } else if (this.type === "datetime") {
        list = [
          dayjs().year() - dayjs(val).year() + this.minYear,
          dayjs(val).month(),
          dayjs(val).date() - 1,
          dayjs(val).hour(),
          dayjs(val).minute()
        ]

      } else {
        list = [
          dayjs(val).hour(),
          dayjs(val).minute(),
        ]

      }
      if (this.showSecond) {
        list.push(dayjs(val).second())
      }
      return list
    },
    // formatTime(val) {
    //   if (dayjs(val).year() === dayjs().year()) {
    //     return dayjs(val).locale("zh-cn").format("YY[年]M[月]D[日]");
    //   } else {
    //     return dayjs(val).locale("zh-cn").format("YY[年]M[月]D[日]");
    //   }
    // },
    createYear(left_offset, right_offset) {
      const current_year = dayjs().year();
      let list = [];
      let start = current_year - left_offset;
      const end = current_year + right_offset;
      while (start <= end) {
        list.push(start);
        start++;
      }
      this.yearList = list;
    },

    createMonth() {
      let list = [];
      let start = 1;
      while (start <= 12) {
        list.push(start < 10 ? "0" + start : start);
        start++;
      }
      this.monthList = list
    },
    creatDay(day = "") {
      let list = [];
      let start = 1;
      const getMaxDay = () => {
        let current_year = dayjs().year();
        if (day) {
          current_year = dayjs(day).year();
        }
        const current_month = dayjs(this.value).month() + 1;
        const max_day_month = [1, 3, 5, 7, 8, 10, 12];
        if (max_day_month.includes(current_month)) {
          return 31;
        } else if (current_month === 2) {
          return current_year % 4 == 0 ? 29 : 28;
        } else {
          return 30;
        }
      };
      while (start <= getMaxDay()) {
        list.push(start < 10 ? "0" + start : start);
        start++;
      }
      this.dayList = list
    },
    creatHour() {
      this.hourList = [...new Array(24).keys()].map((_item, index) => {
        if (index <= 9) {
          return "0" + index;
        } else {
          return "" + index;
        }
      });
    },
    creatMinute() {
      this.minuteList = [...new Array(60).keys()].map((_item, index) => {
        if (index <= 9) {
          return "0" + index;
        } else {
          return "" + index;
        }
      });
    },
    creatSecond() {
      this.secondList = [...new Array(60).keys()].map((_item, index) => {
        if (index <= 9) {
          return "0" + index;
        } else {
          return "" + index;
        }
      });
    },
    pickerClick() {
      if (!this.disabled) {
        this.show = true;
        if (!this.value && !this.defaultValue) {
          const day = dayjs()
          this.pickerValue = this.renderPickerValue(day)
          const pickerValue = this.pickerValue
          if (this.type === "time") {
            this.tempValue = `${this.hourList[pickerValue[0]]}:${this.minuteList[pickerValue[1]]}:${this.showSecond ? this.secondList[pickerValue[2]] : '00'}`
          } else {
            this.tempValue = `${this.yearList[pickerValue[0]]}-${this.monthList[pickerValue[1]]}-${this.dayList[pickerValue[2]]} ${this.hourList[pickerValue[3]]}:${this.minuteList[pickerValue[4]]}:${this.showSecond ? this.secondList[pickerValue[5]] : '00'}`

          }
          // this.tempValue = `${this.dayList[pickerValue[0]]} ${this.hourList[pickerValue[1]]}:${this.minuteList[pickerValue[2]]}:${this.showSecond ? this.secondList[pickerValue[3]] : '00'}`
        }
      }
    },
    onChange(e) {
      // console.log(e);
      const value = e.detail.value

      if (this.type === "time") {
        this.tempValue = `${this.hourList[value[0]]}:${this.minuteList[value[1]]}:${this.showSecond ? this.secondList[value[2]] : '00'}`
      } else {
        this.tempValue = `${this.yearList[value[0]]}-${this.monthList[value[1]]}-${this.dayList[value[2]]} ${this.hourList[value[3]]}:${this.minuteList[value[4]]}:${this.showSecond ? this.secondList[value[5]] : '00'}`

      }
      console.log(this.tempValue)
      // console.log(this.tempValue)
      // console.log(this.dayList[e.detail.current+2])
    },
    onConfirmSelect() {
      this.show = false
      let value = dayjs(this.tempValue).format(this.valueFormat)
      if (this.type === "time") value = this.tempValue
      this.$emit('input', value) //兼容小程序的双向绑定
      this.$emit('change', value)
    },
    handleClear() {
      this.$emit('input', "")
      this.$emit('change', "")
    },
  },
};
</script>

<style scoped lang="scss">
.picker-view {
  width: 100%;
  height: 600rpx;
  margin-top: 20rpx;

  .item {
    height: 40px;
    line-height: 40px;
    text-align: center;
    font-size: 28rpx;
  }

  .column {
    display: inline-block;
  }

  .day {
    flex: 4;
    width: 40%;
  }

  .hour {
    flex: 3;
    width: 30%;
  }

  .minute {
    flex: 3;
    width: 30%;
  }

  .second {
    flex: 3;
    width: 30%;
  }
}

.option_list {

  // #ifdef H5
  // margin-bottom: 50px;
  // #endif
  &.has_bottombar {
    margin-bottom: 50px;
  }

  background-color: #fff;

  .header {
    // padding: 24rpx;
    justify-content: space-between;
    font-size: 28rpx;
    border-top: 4rpx solid #409eff;
    background-image: linear-gradient(0deg,
        rgba(246, 246, 246, 0) 0%,
        rgba(#409eff, 0.1) 100%);

    .tip {
      padding: 24rpx 0;
      flex: 1;
      text-align: center;
      color: #333;
    }

    .cancel_btn {
      padding: 24rpx;
      color: #888;
    }

    .ok_btn {
      padding: 24rpx;
      color: #409eff;
      transition: 0.26s;

      &.disabled {
        opacity: 0.6;
      }
    }
  }

  .search_box {
    display: flex;
    align-items: center;
    padding: 12rpx 86rpx;
    border-bottom: 1rpx solid #f3f3f3;

    input {
      flex: 1;
      height: 66rpx;
      padding: 12rpx 12rpx;
      font-size: 26rpx;
      background-color: #f7f7f7;
    }

    .search-btn {
      line-height: 60rpx;
      padding: 0 28rpx;
      margin-left: 24rpx;
      border-radius: 6rpx;
      // border: 1rpx solid #409eff;
      // color: #409eff;
      border: 1rpx solid #409eff;
      color: #409eff;
      transition: 0.26s;

      &.disabled {
        opacity: 0.6;
      }
    }
  }

  .content {
    max-height: 35vh;
    min-height: 320rpx;
    padding: 0 48rpx;

    .item {
      display: flex;
      flex-direction: row;
      justify-content: space-between;
      align-items: center;
      padding: 24rpx 0;

      ::v-deep .icon {
        display: none;
      }

      &.active {
        color: #409eff;

        ::v-deep .icon {
          display: block;
          color: #409eff;
        }
      }

      &.disabled {
        color: #999;
      }

      .text {
        margin-right: 16rpx;
      }
    }
  }
}

.flex-row {
  display: flex;
  flex-direction: row;
}

label {
  font-size: 22rpx;
  color: #666;
  margin-bottom: 24rpx;
}

.select-box {
  width: 100%;
  // padding: 24rpx 0;
}

.one_row {
  width: 100%;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  padding: 0;

  label {
    margin-bottom: 0;
    font-size: 26rpx;
    color: #666;
    margin-right: 24rpx;
  }

  .select-row {
    flex: 1;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;

    &.border {
      padding: 12rpx;
      border-radius: 12rpx;
      border: 1rpx solid #f3f3f3;
    }

    &.disabled {
      background-color: #f3f3f3;
    }

    picker {
      overflow: hidden;

      view {
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        word-break: break-all;
        // text-align: right;
        font-size: 28rpx;
        // color: #999;
      }
    }

    &.large {
      border-radius: 8rpx;
      padding: 12rpx 16rpx;
      font-size: 28rpx;

      view {
        font-size: 28rpx;
      }

      .arrow {
        font-size: 28rpx;
      }
    }

    &.big {
      border-radius: 8rpx;
      padding: 12rpx 16rpx;
      font-size: 32rpx;

      view {
        font-size: 32rpx;
      }

      .arrow {
        font-size: 32rpx;
      }
    }

    &.small {
      border-radius: 8rpx;
      padding: 6rpx 12rpx;
      font-size: 24rpx;

      view {
        font-size: 24rpx;
      }

      .arrow {
        font-size: 24rpx;
      }
    }
  }
}

.select-row {
  align-items: center;
  // line-height: 62upx;
  background-color: #fff;

  &.border {
    padding: 12rpx;
    border-radius: 12rpx;
    border: 1rpx solid #f3f3f3;
  }

  &.disabled {
    background-color: #f3f3f3;
  }

  .select {
    flex: 1;
    font-size: 26rpx;
  }

  .items-center {
    align-items: center;
  }

  picker {
    flex: 1;

    // height: 62upx;
    view {
      font-size: 28rpx;
    }
  }

  .hasvalue {
    flex-shrink: 0;
    flex: 1;
  }

  .novalue {
    flex-shrink: 0;
    flex: 1;
    font-size: 26rpx;
    color: #8a929f;
  }

  // .clear_btn{
  // 	padding: 2rpx;
  // }

  .unit {
    margin-left: 10rpx;
    font-size: 24rpx;
    color: #f3f3f3;
  }

  uni-icon {
    line-height: 62rpx;
    margin-left: 10rpx;
  }

  &.big {
    border-radius: 8rpx;

    .novalue {
      font-size: 32rpx;
    }

    .hasvalue {
      font-size: 32rpx;
    }

    &.border {
      padding: 12rpx;
    }
  }

  &.large {
    border-radius: 8rpx;

    .hasvalue {
      font-size: 28rpx;
    }

    .novalue {
      font-size: 28rpx;
    }

    &.border {
      padding: 12rpx;
    }
  }

  &.small {
    border-radius: 8rpx;

    .hasvalue {
      font-size: 24rpx;
    }

    .novalue {
      font-size: 24rpx;
    }

    &.border {
      padding: 4rpx;
    }
  }
}

.bottom-line {
  position: relative;
  padding: 12rpx;
  background-color: #fff;

  &::after {
    content: "";
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 1rpx;
    -webkit-transform: scaleY(0.5);
    transform: scaleY(0.5);
    background-color: #f3f3f3;
  }
}
</style>
